#include "dicom/handler/readdir_handler.h"

#include <boost/bind.hpp>
#include <gwbase/base/util.h>
#include <gwbase/base/logging.h>
#include <json/json.h>
#include "dicom/web_server.h"
#include "dicom/session.h"
#include "dicom/handler/handler_common.h"
#include "dicom/dmv_db.h"

namespace dicom {

static HttpHandler* CreateReaddirHander(onion_request* conn) {
  return new ReaddirHandler(conn);
}

void ReaddirHandler::RegisterHandler(WebServer* s) {
  s->AddHandler("/api/folder/readdir", "GET",
                boost::bind(CreateReaddirHander, _1));
}

int ReaddirHandler::HandleRequest(onion_request* conn, onion_response* resp) {
  Status s;
  CredentialPtr c;

  s = CheckToken(conn, &c);
  if (!s.ok()) {
    SendSimpleResponse(resp, 401, "oauth error");
    return OCS_PROCESSED;
  }

  const std::string pid = GetQueryString(conn, "pid");
  if (pid.empty()) {
    LOG_WARN << "pid is empty";
    SendSimpleResponse(resp, 400, "pid is empty");
    return OCS_PROCESSED;
  }

  LOG_DEBUG << "REQUEST READDIR: " << pid;

  Json::Value v;
  v["code"] = 0;
  v["items"] = Json::Value(Json::arrayValue);
  Json::Value& items = v["items"];

  DmvDBPtr db = GetGateway()->dmv_mgr()->GetDB(c->email);
  DirObject d;
  if (db->GetDirByID(pid, &d) == false) {
    SendSimpleResponse(resp, 404, "invalid directory id");
    return OCS_PROCESSED;
  }

  LogHippaOperation(OP_LIST_FILE, db, c, d.parentId, d.name);

  std::vector<FileObject> files;
  std::vector<DirObject> dirs;
  db->GetSubItems(pid, &dirs, &files);

  for (size_t i = 0; i < dirs.size(); ++i) {
    Json::Value v;
    const DirObject& d = dirs[i];
    d.ToJson(v);
    items.append(v);
  }

  for (size_t i = 0; i < files.size(); ++i) {
    Json::Value v;
    const FileObject& fo = files[i];
    fo.ToJson(v);
    items.append(v);
  }

  SendJsonResult(resp, 200, v);
  return OCS_PROCESSED;
}
}
